<template>
	<header>
		<div class="search-return" @click="goBack">
			<i class="iconfont icon-back"></i>
		</div>
		<div class="search-main">
			<i class="iconfont icon-fangdajing"></i>
			<form action="" onsubmit='return false' @keyup.enter="goSearchList">
				<input type="text" placeholder="搜索您喜欢的产品" v-model="searchValue" autofocus ref="myInput">
				<!-- <input type="search" placeholder="搜索您喜欢的产品" v-model="searchValue" autofocus> -->
			</form>
		</div>
		<div class="search-btn" @click="goSearchList">搜索</div>
	</header>
	
</template>

<script>
	export default{
		data(){
			return{
				searchValue:this.$route.query.key || '',
				searchArr:[]
			}
		},
		mounted() {
		    // 键盘监听事件
		    window.addEventListener("touchmove", this.myTouchMove, true);
		    },
		methods:{
			//失去焦点
			myTouchMove() {
			    this.$refs.myInput.blur();
			},
			goBack(){
				this.$router.back();
			},
			goSearchList(){
				
				//如果没有搜索内容，那就直接return
				if( !this.searchValue ) return;
				//判断之前有无搜索的本地存储
				if( !localStorage.getItem('searchList') ){
					//没有
					localStorage.getItem('searchList','[]');
				}else{
					//之前搜索过
					this.searchArr =  JSON.parse( localStorage.getItem('searchList') );
				}
				//增加数据(给数组添加)
				this.searchArr.unshift( this.searchValue );
				//ES6去重
				let newArr = new Set( this.searchArr);
				//给本地存储赋值(通过newArr把数组转换为一个真正的数组)
				localStorage.setItem('searchList',JSON.stringify(Array.from(newArr)));
				
				//如果当前页面和我搜索的页面一致,及路径如果没有变化，不跳转页面(解决在搜索结果页面重复搜索相同内容时报错)
				if( this.searchValue === this.$route.query.key ) return;
				//跳转页面
				this.$router.push({
					name:'list',
					query:{
						key:this.searchValue
					}
				})
			}
		}
	}
</script>

<style scoped>
	header{
		display: flex;
		justify-content: space-between;
		width: 100%;
		height: 1.173333rem;
		color:#fff;
		background-color: #b0352f;
	}
	.search-return{
		padding: 0.16rem 0.266667rem;
	}
	.search-return i{
		font-size: 0.586667rem;
	}
	.search-main{
		display: flex;
		align-items: center;
		width: 6.666667rem;
		height: 0.8rem;
		margin: 0.16rem 0;
		border-radius: 12px;
		background-color: #fff;
	}
	.search-main i{
		padding: 0 0.266667rem;
		color: #666;
	}
	.search-main form{
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
	}
	.search-main form input{
		width: 100%;
	}
	.search-btn{
		padding: 0.266667rem 0.266667rem;
		font-size: 0.426667rem;
	}
</style>